const path = require('path');
const glob = require('glob');
const UglifyJs = require("uglify-js");
const UglifyCss = require("uglifycss");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const {CleanWebpackPlugin} = require("clean-webpack-plugin");
const CompressionWebpackPlugin = require('compression-webpack-plugin');
const fs = require("fs");
const {
	VueLoaderPlugin
} = require('vue-loader')

module.exports = (env, options) => {
	const devMode = options.mode !== 'production';
	const multyPageConfig = () => {
		const entrys = {};
		const htmlWebpackPlugins = [];
		const jsFiles = glob.sync(path.join(__dirname, './js/pages/*.src.js'));
		Object.keys(jsFiles).map(index => {
			const file = jsFiles[index];
			const match = file.match(/\/js\/pages\/(.*)\.src\.js/);
			const filename = match && match[1];
			entrys['js/pages/' + filename] = file;
		});
		return {
			entrys,
			htmlWebpackPlugins
		}
	};

	const {entrys} = multyPageConfig();
	const multyEntrys = Object.assign({}, entrys);
	const toPc = path.resolve(__dirname, './dist');

	if (!devMode) {
		let loaderContent = fs.readFileSync(path.resolve(__dirname, 'js/loader.js'), "utf8");
		let loaderGettor = loaderContent.match(/Loader\.dev\?Loader\.get\(([\s\S]*)\)\:/);
		loaderGettor = loaderGettor && loaderGettor[1];
		const writeCommonFile = function () {
			if (!!loaderGettor) {
				loaderGettor = loaderGettor.replace(/\"/g, '').split(',');
				let jsContext = [];
				let cssContext = [];
				loaderGettor.map((l) => {
					l = l.replace(/(^\s*)|(\s*$)/g, '');
					let m = l.match(/[^\.]\w*$/);
					let ext = m && m[0];
					if (ext === 'js') {
						let j = fs.readFileSync(path.resolve(__dirname, 'js/' + l), "utf8");
						jsContext.push(j);
					}
					if (ext === 'css') {
						let c = fs.readFileSync(path.resolve(__dirname, 'css/' + l), "utf8")
						cssContext.push(c);
					}
				});
				jsContext = jsContext.join('');
				fs.writeFile(path.resolve(__dirname, 'js/common.min.js'), UglifyJs.minify(jsContext).code, 'utf8', function (error) {
					if (error) {
						console.log(error);
						return false;
					}
					console.log('写入common.min.js成功');
				});

				cssContext = cssContext.join('');
				//cssContext = cssContext.replace(/\.\.\/images/g, 'pc/images');
				fs.writeFile(path.resolve(__dirname, 'css/common.min.css'), UglifyCss.processString(cssContext), 'utf8', function (error) {
					if (error) {
						console.log(error);
						return false;
					}
					console.log('写入common.min.css成功');
				});
			}
		};
		writeCommonFile();
	}
	return {
		optimization: {
			minimize: true,
			minimizer: [
				new TerserPlugin({
					cache: true,
					parallel: true,
					sourceMap: devMode,
					test: /\.js(\?.*)?$/i,
					terserOptions: {
						format: {
							comments: false
						}
					},
					extractComments: false
				}),
				new OptimizeCSSAssetsPlugin({})
			]
		},
		entry: multyEntrys,
		output: {
			filename: '[name].min.js',
			path: path.resolve(__dirname, './dist'),
			publicPath: ''
		},
		devtool: devMode ? 'eval-cheap-module-source-map' : undefined,
		module: {
			rules: [
				{
					test: /\.vue$/,
					loader: 'vue-loader'
				},
				{
					test: /\.js$/,
					exclude: /node_modules/,
					use: {
						loader: 'babel-loader'
					}
				},
				{
					test: /\.[s]?css$/,
					use: [
						MiniCssExtractPlugin.loader,
						'css-loader',
						'sass-loader',
					],
				},
				{
					test: /\.(jpg|gif|png|svg)$/,
					use: {
						loader: 'url-loader',
						options: {
							limit: 8192,
							name: '[hash:8][name].[ext]',
							outputPath: '../images/hash',
						}
					}
				},
				{
					test: /\.(ttf|eot|woff|woff2)$/,
					use: {
						loader: 'url-loader'
					}
				}
			]
		},
		plugins: [
			// 自动清理 dist 文件夹
			new VueLoaderPlugin(),
			new CopyWebpackPlugin([{
				from: 'css/plugins/*.css',
				to: path.resolve(__dirname, './dist/'),
				transform(css) {
					return UglifyCss.processString(css.toString());
				}
			}, {
				from: 'css/common.min.css',
				to: path.resolve(__dirname, './dist/css/')
			}, {
				from: 'images/',
				to: path.resolve(__dirname, './dist/images')
			}, {
				from: 'fonts/',
				to: path.resolve(__dirname, './dist/fonts')
			}, {
				from: 'js/common.min.js',
				to: path.resolve(__dirname, './dist/js/')
			}, {
				from: 'js/loader.js',
				to: path.resolve(__dirname, './dist/js/'),
				transform(js, filePath) {
					const match = /\/js\/loader.js/.test(filePath);
					js = js.toString();
					if (!!match) {
					  js = js.replace(/dev\:\!0/, 'dev:0').replace(/p\:\"\"/, 'p:"pc/"').replace(/c\:\"dev\_([\d]+)\.([\d]+)\.([\d]+)\"/, 'c:"online_' + new Date().getTime() + '"');
          }
					return UglifyJs.minify(js).code;
				}
			}, {
				from: '*.html',
				to: path.resolve(__dirname, './dist/')
			}])
		]
	}
};
